import { Snackbar } from "@varlet/ui";
import { ElMessage } from "element-plus";
import { Base64 } from "js-base64";

export const copy = (text) => {
    const textarea = document.createElement("textarea");
    textarea.value = text;
    textarea.style.position = "fixed";
    textarea.style.right = "1000px";
    document.body.appendChild(textarea);
    textarea.select();
    document.execCommand("copy");
    document.body.removeChild(textarea);
};

export const download = (url, filename) => {
    const link = document.createElement("a");
    link.href = url;
    link.download = filename;
    link.click();
};

export const alipayForm = (aliPayForm, isNewTab = true) => {
    const aliPayBox = document.getElementById("aliPayForm");
    if (isNewTab)
        aliPayForm = aliPayForm.replace("<form", '<form target="_blank"');
    const div = document.createElement("div"); // 创建div
    div.id = "aliPayForm";

    if (aliPayBox) {
        aliPayBox.removeChild(document.querySelector("#aliPayForm form"));
        aliPayBox.innerHTML = aliPayForm;
        document.querySelector("#aliPayForm form").submit();
        return;
    }
    div.innerHTML = aliPayForm;
    document.body.appendChild(div);
    document.querySelector("#aliPayForm form").submit();
};

export const isEmpty = (str) => {
    return !str || str.trim().length === 0;
};

export const isPhone = (num) => {
    return /^1[3456789]\d{9}$/.test(num);
};

export const getTopDistance = (element) => {
    var distance = element.offsetTop;
    while (element.offsetParent) {
        element = element.offsetParent;
        distance += element.offsetTop;
    }
    return distance;
};

export const getLeftDistance = (element) => {
    var distance = element.offsetLeft;
    while (element.offsetParent) {
        element = element.offsetParent;
        distance += element.offsetLeft;
    }
    return distance;
};

export const GetUrlParams = (href) => {
    const url = new URL(href);
    return {
        origin: url.origin,
        search: url.search.slice(1),
    };
};

const LoginMobile = async (cancelBtn) => {
    const router = useRouter();
    const pageStore = usePageStore();

    Dialog({
        title: "提示",
        message: "请先登录",
        "confirm-button-text": "去登录",
        "cancel-button-text": !cancelBtn ? "返回" : "取消",
        closeOnClickOverlay: false,
        teleport: "body",
        overlayStyle: !cancelBtn
            ? {
                "backdrop-filter": "blur(10px)",
            }
            : {},
    })
        .then((type) => {
            if (type === "confirm") {
                navigateTo("/login.html");
                typeof pageStore.onConfirm && pageStore.onConfirm();
            } else if (type === "cancel") {
                if (!cancelBtn) {
                    router.back();
                }
            }
        })
        .catch(() => { });
};

export const LoginModal = (
    cancelBtn = true,
    urlParams = {},
    scoreParams = {},
    open = false,
    onConfirm
) => {
    const pageStore = usePageStore();
    const dialogStore = useDialogStore();

    pageStore.urlParams = urlParams;
    pageStore.scoreParams = scoreParams;
    pageStore.isLoginOpen = open;
    pageStore.onConfirm = onConfirm;

    if (pageStore.isMobile) {
        LoginMobile(cancelBtn);
    } else {
        dialogStore.isLoginTipsDialogVisible = true;
        dialogStore.loginCancelBtn = cancelBtn;
    }
};

export const formatDate = (date, format) => {
    const dayjs = useDayjs();
    return dayjs(date).utc().local().format(format);
};

export const Message = () => {
    const pageStore = usePageStore();
    return pageStore.isMobile ? Snackbar : ElMessage;
};

export const IsWeiXin = () =>
    /MicroMessenger/i.test(window.navigator.userAgent);

export const IsAlipay = () => /AlipayClient/i.test(window.navigator.userAgent);

export const generateRandomString = (length) => {
    var result = "";
    var characters =
        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
    for (var i = 0; i < length; i++) {
        var randomIndex = Math.floor(Math.random() * characters.length);
        result += characters.charAt(randomIndex);
    }
    return result;
};

export const formatFileSize = (bytes) => {
    const units = ["B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"];
    let size = bytes;
    let unitIndex = 0;

    while (size >= 1024 && unitIndex < units.length - 1) {
        size /= 1024;
        unitIndex++;
    }

    // 保留两位小数，四舍五入
    size = Math.round(size * 100) / 100;

    return `${size} ${units[unitIndex]}`;
};

export const getWatermarkImage = (url, width = "", root = "image") => {
    if (process.env.NODE_ENV === "development") return url;
    return url
        ? url.replace(
            /^https?:\/\/\w+?\.\w+?\.com\/+uploads\/(.+)/,
            _cdn_ + "/" + root + "/$1?w=" + width
        )
        : "";
};

export const addBaiduCustomer = () => {
    const pageStore = usePageStore();
    const hm = document.createElement("script");
    hm.src = "https://hm.baidu.com/hm.js?c7943ec1e691843158f4965ac279e8e6";
    hm.onload = () => {
        pageStore.baiduCustomer = true;
        console.log("百度客服加载成功...");
    };
    document.head.appendChild(hm);
};

export function toBase64(str) {
    return Base64.encode(str, true);
}

// 产生一个随机的uuid
export const uuid = () => {
    return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(
        /[xy]/g,
        function (c) {
            var r = (Math.random() * 16) | 0,
                v = c == "x" ? r : (r & 0x3) | 0x8;
            return v.toString(16);
        }
    );
};

function addZero(num) {
    return num < 10 ? "0" + num : num;
}

export const handlerDate = (dateStr) => {
    const date = new Date(dateStr);
    const year = date.getFullYear();
    const month = date.getMonth() + 1;
    const day = date.getDate();
    const hour = date.getHours();
    const minute = date.getMinutes();

    const now = new Date();
    const nowYear = now.getFullYear();

    let _str = "";
    if (year != nowYear) {
        _str = year + '-'
    };

    _str += addZero(month) + '-' + addZero(day) + ' ' + addZero(hour) + ':' + addZero(minute);

    return _str;
}

function _registerEvent(target, eventType, cb) {
    if (target.addEventListener) {
        target.addEventListener(eventType, cb);
        return {
            remove: function () {
                target.removeEventListener(eventType, cb);
            }
        };
    } else {
        target.attachEvent(eventType, cb);
        return {
            remove: function () {
                target.detachEvent(eventType, cb);
            }
        };
    }
}

/**
 * uri 打开客户端的uri
 * failCb 打开客户端失败回调
 * successCb 打开客户端成功回调
 */
export function openUriWithInputTimeoutHack(uri, failCb, successCb) {
    let target = document.createElement('input')
    target.style.width = '0'
    target.style.height = '0'
    target.style.position = 'fixed'
    target.style.top = '0'
    target.style.left = '0'
    document.body.appendChild(target)

    target.focus();
    var handler = _registerEvent(target, "blur", onBlur);
    function onBlur() {
        successCb && successCb()
        handler.remove()
        clearTimeout(timeout)
        document.body.removeChild(target)
    };

    location.href = uri

    var timeout = setTimeout(function () {
        failCb && failCb()
        handler.remove()
        document.body.removeChild(target)
    }, 1000);
}

export const timeDifference = (datetime) => {
    const date = new Date(datetime);
    const now = new Date();
    const seconds = Math.floor((now - date) / 1000);

    const intervals = {
        year: 31536000,
        month: 2592000,
        week: 604800,
        day: 86400,
        hour: 3600,
        minute: 60,
        second: 1
    };

    if (seconds <= 45) {
        return '几秒前';
    } else if (seconds > 45 && seconds <= 90) {
        return '1分钟前';
    } else if (seconds > 90 && seconds <= 3600) {
        return `${Math.floor(seconds / intervals.minute)} 分钟前`;
    } else if (seconds > 3600 && seconds <= 5400) {
        return '1小时前';
    } else if (seconds > 5400 && seconds <= 86400) {
        return `${Math.floor(seconds / intervals.hour)} 小时前`;
    } else if (seconds > 86400 && seconds <= 129600) {
        return '1天前';
    } else if (seconds > 129600 && seconds <= 604800) {
        return `${Math.floor(seconds / intervals.day)} 天前`;
    } else if (seconds > 604800 && seconds <= 1209600) {
        return '1周前';
    } else if (seconds > 1209600 && seconds <= 2592000) {
        return `${Math.floor(seconds / intervals.week)} 周前`;
    } else if (seconds > 2592000 && seconds <= 3888000) {
        return '1个月前';
    } else if (seconds > 3888000) {
        return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
    }
}
